package org.gp.core.utils;

import com.thoughtworks.xstream.XStream;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.gp.core.entity.TextMessage;
import org.gp.core.entity.enums.MessageEnum;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by luoliang on 2017/2/12.
 */
@Slf4j
public class MessageUtil {

    public static Map<String, String> xmlToMap(HttpServletRequest request) {
        Map<String, String> map = new HashMap<>();
        SAXReader reader = new SAXReader();

        InputStream ins = null;
        Document doc = null;
        try {
            ins = request.getInputStream();
            doc = reader.read(ins);
            Element root = doc.getRootElement();

            List<Element> list = root.elements();

            for (Element e : list) {
                map.put(e.getName(), e.getText());
            }

            ins.close();
        } catch (IOException e) {
            log.error("xmlToMap IOExceptio:", e);
        } catch (DocumentException e1) {
            log.error("xmlToMap DocumentException:", e1);
        }

        return map;
    }

    // 文本对象转换为xml方法
    public static String textMessageToXml(TextMessage textMessage) {
        XStream xstream = new XStream();
        xstream.alias("xml", textMessage.getClass());
        return xstream.toXML(textMessage);
    }

    public static String initText(String ToUserName, String FromUserName,
                                  String Content) {
        TextMessage text = new TextMessage();
        text.setFromUserName(ToUserName);
        text.setToUserName(FromUserName);
        text.setMsgType(MessageEnum.MESSAGE_TEXT.getDesc());
        text.setCreateTime(new Date().getTime());
        text.setContent(Content);

        return MessageUtil.textMessageToXml(text);
    }

    // 主菜单
    public static String menuText() {
        StringBuffer sb = new StringBuffer();
        sb.append("欢迎您的关注~等你好久了~~\n");
        sb.append("本微信平台为自主开发，请放心使用。\n");
        sb.append("所有功能请在菜单栏进行点击体验。\n");
        sb.append("发送“菜单”，“menu”可获取本菜单~\n");
        sb.append("更多功能尽请期待...");

        return sb.toString();
    }
}
